import unittest
import os
import time
from utils.logger import Logger  # 确保正确导入你的 Logger 类
import uuid  # 生成唯一 ID


class TestLogger(unittest.TestCase):

    def setUp(self):
        self.log_file = f'./test_logger_{uuid.uuid4().hex}.log'  # 每次测试创建唯一日志文件

        # **手动创建空日志文件**
        with open(self.log_file, 'w') as f:
            pass

        self.logger = Logger(self.log_file).get_logger()
        self.logger.info("Test log entry")

        # **确保日志文件成功写入**
        for handler in self.logger.handlers:
            handler.flush()
            handler.close()  # 强制关闭文件

        # **等待 1秒，确保日志落盘**
        time.sleep(1)

        self.assertTrue(os.path.exists(self.log_file), "Logger did not create the log file.")

    def test_log_file_creation(self):
        """测试日志文件是否正确创建"""
        self.assertTrue(os.path.exists(self.log_file), "Log file was not created.")

    def test_log_message_format(self):
        """测试日志格式是否正确"""
        with open(self.log_file, 'r') as file:
            log_content = file.read()

        # 检查日志中是否包含预期的信息
        self.assertIn('TransformerLogger', log_content)  # 检查是否包含记录器名称
        self.assertIn('INFO', log_content)  # 检查是否包含日志级别
        self.assertIn('Test log entry', log_content)  # 检查是否包含日志内容

    def test_log_levels(self):
        """测试不同级别的日志是否正确记录"""
        log_messages = {
            "DEBUG": "Debug message",
            "INFO": "Info message",
            "WARNING": "Warning message",
            "ERROR": "Error message",
            "CRITICAL": "Critical message"
        }

        # 记录所有日志级别的日志
        for level, msg in log_messages.items():
            getattr(self.logger, level.lower())(msg)  # 动态调用日志方法

        # 确保日志写入文件
        for handler in self.logger.handlers:
            handler.flush()
            handler.close()  # 强制关闭文件，确保写入磁盘

        # 等待日志写入
        time.sleep(1)

        # 读取日志文件内容
        with open(self.log_file, 'r') as file:
            log_content = file.read()

        # 先检查日志文件是否为空
        self.assertNotEqual(log_content.strip(), "", "Log file is empty!")

        # 检查每个日志级别是否写入
        for level, msg in log_messages.items():
            self.assertIn(f"{level} - {msg}", log_content, f"Missing {level} log")

    def tearDown(self):
        """清理日志文件，避免污染测试环境"""
        for handler in self.logger.handlers[:]:
            handler.close()
            self.logger.removeHandler(handler)
        # 删除日志文件
        if os.path.exists(self.log_file):
            os.remove(self.log_file)
